package com.wss.lsl.test.driven.scoketio.tcp;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class HelloServerIo {

	private static final String UTF8 = "UTF-8";

	@SuppressWarnings("resource")
	public static void main(String[] args) throws Exception {

		ServerSocket so = new ServerSocket(8888);
		final Socket s = so.accept();

		System.out.println("after accept");
		new Thread(new Runnable() {

			@Override
			public void run() {
				System.out.println("enter run");
				BufferedReader br = null;
				BufferedWriter bw = null;
				try {
					br = new BufferedReader(new InputStreamReader(
							s.getInputStream(), UTF8));
					bw = new BufferedWriter(new OutputStreamWriter(
							s.getOutputStream(), UTF8));
					String content = null;
					boolean f = true;
					System.out.println("get br and bw");
					while ((content = br.readLine()) != null && f) {
						// readLine()将阻塞，等待客户端的输入
						System.out.println(content);
						bw.write(content);
						bw.write("\n");
						bw.flush();
						if ("bye".equals(content)) {
							f = false;
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					try {
						if (br != null) {
							br.close();
						}
						if (bw != null) {
							bw.close();
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}
}
